<script setup lang="ts">
import type {
  BookSetRespVO,
  BookSetSearchParams,
  CategoryRespVO,
} from '@/api/types/book'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { ref } from 'vue'
import {
  getBookSetPage,
  getCategoryList,
  recordSearchHistory,
  searchBookSets,
} from '@/api/book'

// 页面参数
interface PageParams {
  category?: string
  language?: string
  keyword?: string
  type?: string
}

// 页面状态
const searchKeyword = ref('')
const currentCategory = ref('全部')
const currentCategoryId = ref<number | undefined>(undefined)
const currentLanguage = ref<'english' | 'chinese'>('english')
const currentType = ref('')
const searchPlaceholder = ref('搜索绘本集')

// 列表数据
const bookSetList = ref<BookSetRespVO[]>([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)
const loading = ref(false)

// 分类数据
const categoryList = ref<CategoryRespVO[]>([])

// 筛选条件
const showFilters = ref(false)

// 加载分类列表
async function loadCategories(): Promise<void> {
  try {
    // API层已经处理了语言映射
    const response = await getCategoryList(currentLanguage.value)

    if (response.code === 0 && response.data) {
      // 后端已经根据语言过滤了数据，直接使用
      categoryList.value = response.data

      // 检查是否已经存在"全部"分类
      const hasAllCategory = categoryList.value.some(category => category.name === '全部')

      // 只有当不存在"全部"分类时才添加
      if (!hasAllCategory) {
        categoryList.value.unshift({
          id: 0,
          name: '全部',
          language: currentLanguage.value === 'chinese' ? 'zh' : 'en',
          sortOrder: 0,
          icon: 'icon-qiehuankapian',
          description: `所有${currentLanguage.value === 'chinese' ? '中文' : '英文'}绘本分类`,
        } as any)
      }

      // 如果有传入的分类名称，找到对应的分类ID
      if (currentCategory.value && currentCategory.value !== '全部') {
        const targetCategory = categoryList.value.find(category => category.name === currentCategory.value)
        if (targetCategory) {
          currentCategoryId.value = targetCategory.id
          console.log('找到分类ID:', currentCategoryId.value, '分类名称:', currentCategory.value)
        }
        else {
          console.warn('未找到分类:', currentCategory.value)
          // 如果找不到对应分类，重置为"全部"
          currentCategory.value = '全部'
          currentCategoryId.value = undefined
        }
      }
    }
  }
  catch (error) {
    console.error('加载分类失败:', error)
    uni.showToast({
      title: '加载分类失败',
      icon: 'none',
    })
  }
}

// 加载数据
async function loadData(reset = false) {
  if (loading.value)
    return

  loading.value = true

  try {
    let response: any

    if (searchKeyword.value.trim()) {
      // 搜索模式
      const searchParams = {
        keyword: searchKeyword.value,
        language: currentLanguage.value,
        pageNo: reset ? 1 : currentPage.value,
        pageSize: pageSize.value,
      }
      response = await searchBookSets(searchParams)
    }
    else {
      // 分页查询模式
      const params: BookSetSearchParams = {
        pageNo: reset ? 1 : currentPage.value,
        pageSize: pageSize.value,
        language: currentLanguage.value,
      }

      // 如果不是"全部"分类，添加分类ID
      if (currentCategoryId.value && currentCategoryId.value > 0 && currentCategory.value !== '全部') {
        params.categoryId = currentCategoryId.value
      }

      response = await getBookSetPage(params)
    }

    if (response.code === 0 && response.data) {
      // 统一处理分页格式的响应
      const isPageResult = !Array.isArray(response.data) && response.data.total !== undefined
      const newData = isPageResult ? (response.data.list || []) : response.data
      const total = isPageResult ? response.data.total : newData.length

      if (reset) {
        bookSetList.value = newData
        currentPage.value = 1
      }
      else {
        // 加载更多时，过滤重复的绘本集
        const existingIds = new Set(bookSetList.value.map(item => item.id))
        const uniqueNewData = newData.filter(item => !existingIds.has(item.id))
        bookSetList.value.push(...uniqueNewData)
      }

      // 更新总数和分页状态
      totalCount.value = total
      hasMore.value = bookSetList.value.length < total

      if (!reset && hasMore.value) {
        currentPage.value++
      }
    }
  }
  catch (error) {
    console.error('加载数据失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'error',
    })
  }
  finally {
    loading.value = false
  }
}

// 加载更多
function loadMore() {
  if (!hasMore.value || loading.value)
    return
  loadData(false)
}

// 搜索输入处理
function onSearchInput() {
  // 实时搜索可以在这里实现防抖
}

// 执行搜索
async function performSearch() {
  if (searchKeyword.value.trim()) {
    // 记录搜索历史
    try {
      await recordSearchHistory(searchKeyword.value.trim())
    }
    catch (error) {
      console.error('记录搜索历史失败:', error)
    }
  }

  currentPage.value = 1
  hasMore.value = true
  showFilters.value = true
  loadData(true)
}

// 切换分类
function switchCategory(category: CategoryRespVO) {
  currentCategory.value = category.name
  currentCategoryId.value = category.id

  // 如果是"全部"分类，将categoryId设为undefined，这样后端会返回所有分类的数据
  if (category.name === '全部') {
    currentCategoryId.value = undefined
  }

  currentPage.value = 1
  hasMore.value = true
  showFilters.value = category.name !== '全部' || searchKeyword.value.trim() !== ''
  loadData(true)
}

// 清空筛选条件
function clearFilters() {
  searchKeyword.value = ''
  currentCategory.value = '全部'
  currentCategoryId.value = undefined
  showFilters.value = false
  currentPage.value = 1
  hasMore.value = true
  loadData(true)
}

// 打开绘本集详情
function openBookSetDetail(bookSet: BookSetRespVO) {
  uni.navigateTo({
    url: `/pages-sub/reading/picture-book-set/index?setId=${bookSet.id}&type=${currentLanguage.value}`,
  })
}

// 页面加载
onLoad((options: PageParams) => {
  // 解析页面参数
  if (options.category) {
    currentCategory.value = decodeURIComponent(options.category)
  }
  if (options.language) {
    currentLanguage.value = options.language as 'english' | 'chinese'
  }
  if (options.keyword) {
    searchKeyword.value = decodeURIComponent(options.keyword)
  }
  if (options.type) {
    currentType.value = options.type
  }

  // 设置搜索提示
  if (currentLanguage.value === 'chinese') {
    searchPlaceholder.value = '搜索中文绘本集'
  }
  else {
    searchPlaceholder.value = '搜索英文绘本集'
  }

  // 显示筛选条件
  if (currentCategory.value !== '全部' || searchKeyword.value) {
    showFilters.value = true
  }

  // 先加载分类列表，再加载绘本集数据
  loadCategories().then(() => {
    loadData(true)
  }).catch((error) => {
    console.error('初始化数据失败:', error)
    // 即使分类加载失败，也尝试加载绘本集数据
    loadData(true)
  })
})

// 触底加载更多
onReachBottom(() => {
  loadMore()
})
</script>

<template>
  <layout-default-uni>
    <view class="category-container">
      <!-- 搜索栏 -->
      <view class="search-bar">
        <view class="search-input-wrapper">
          <input
            v-model="searchKeyword"
            class="search-input"
            type="text"
            :placeholder="searchPlaceholder"
            @input="onSearchInput"
            @confirm="performSearch"
          >
          <view class="search-icon" @click="performSearch">
            <uni-icons type="search" size="20" color="#999" />
          </view>
        </view>
      </view>

      <!-- 分类标签 -->
      <view v-if="categoryList.length > 0" class="category-tabs">
        <scroll-view class="category-scroll" scroll-x>
          <view class="category-list">
            <view
              v-for="category in categoryList"
              :key="category.id"
              class="category-tab"
              :class="{ active: currentCategory === category.name }"
              @click="switchCategory(category)"
            >
              <text class="category-text">
                {{ category.name }}
              </text>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 筛选条件显示 -->
      <view v-if="showFilters" class="filter-bar">
        <view class="filter-item">
          <text class="filter-label">
            分类：
          </text>
          <text class="filter-value">
            {{ currentCategory }}
          </text>
        </view>
        <view v-if="searchKeyword" class="filter-item">
          <text class="filter-label">
            搜索：
          </text>
          <text class="filter-value">
            {{ searchKeyword }}
          </text>
        </view>
        <view class="clear-filters" @click="clearFilters">
          <uni-icons type="close" size="16" color="#fff" />
          <text>清空</text>
        </view>
      </view>

      <!-- 结果统计 -->
      <view class="result-stats">
        <text class="stats-text">
          共找到 {{ totalCount }} 个绘本集
        </text>
      </view>

      <!-- 绘本集列表 -->
      <view class="book-section">
        <view class="book-grid">
          <view
            v-for="bookSet in bookSetList"
            :key="bookSet.id"
            class="book-grid-item"
            @click="openBookSetDetail(bookSet)"
          >
            <view class="book-cover-container">
              <image class="book-cover-grid" :src="bookSet.cover" mode="aspectFill" />
              <view class="book-count-badge">
                {{ bookSet.bookCount }}本
              </view>
            </view>
            <text class="book-title-grid">
              {{ bookSet.title }}
            </text>
            <text class="book-source-grid">
              {{ bookSet.source }}
            </text>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="!loading && bookSetList.length === 0" class="empty-state">
          <view class="empty-icon">
            <uni-icons type="search" size="60" color="#ccc" />
          </view>
          <text class="empty-text">
            暂无相关绘本集
          </text>
          <text class="empty-tip">
            试试其他关键词或分类
          </text>
        </view>

        <!-- 底部加载更多区域 -->
        <view v-if="bookSetList.length > 0" class="bottom-actions">
          <!-- 加载更多按钮 -->
          <view v-if="hasMore" class="load-more-section">
            <view v-if="loading" class="loading-wrapper">
              <uni-icons type="spinner-cycle" size="20" color="#999" />
              <text class="loading-text">
                加载中...
              </text>
            </view>
            <view v-else class="load-more-btn" @click="loadMore">
              <uni-icons type="refreshempty" size="18" color="#4A90E2" />
              <text class="load-more-text">
                点击加载更多
              </text>
            </view>
          </view>

          <!-- 没有更多数据 -->
          <view v-else class="no-more">
            <view class="no-more-line" />
            <text class="no-more-text">
              没有更多数据了
            </text>
            <view class="no-more-line" />
          </view>
        </view>
      </view>
    </view>
  </layout-default-uni>
</template>

<style lang="scss" scoped>
// 导入公共样式变量
@import '@/styles/variables.scss';

.category-container {
  background: $bg-gradient;
  min-height: 100vh;
  padding: $container-padding;
}

/* 搜索栏 - 儿童友好风格 */
.search-bar {
  margin-bottom: $section-margin;

  .search-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background-color: $white;
    border-radius: $border-radius-2xl;
    padding: 0 $spacing-xl;
    box-shadow: $shadow-md;
    border: 1px solid $border-color-light;
    transition: $transition-all;

    &:focus-within {
      border-color: $primary-blue;
      box-shadow: 0 0 0 3px rgba(66, 187, 255, 0.1);
    }

    .search-input {
      flex: 1;
      height: $height-lg;
      font-size: $font-size-base;
      font-family: $font-family;
      border: none;
      outline: none;
      color: $dark-gray;

      &::placeholder {
        color: $medium-gray;
      }
    }

    .search-icon {
      @include center-flex;
      width: 32px;
      height: 32px;
      color: $medium-gray;
      transition: $transition-all;

      &:active {
        transform: scale(0.95);
        color: $primary-blue;
      }
    }
  }
}

/* 分类标签 */
.category-tabs {
  margin-bottom: $section-margin;

  .category-scroll {
    white-space: nowrap;
  }

  .category-list {
    display: flex;
    gap: $spacing-sm;
    padding: 0 $container-padding;
  }

  .category-tab {
    flex-shrink: 0;
    padding: $spacing-sm $spacing-lg;
    background: rgba(255, 255, 255, 0.8);
    border-radius: $border-radius-full;
    border: 1px solid $border-color-light;
    transition: $transition-all;

    &.active {
      background: $blue-gradient;
      border-color: $primary-blue;
      box-shadow: $shadow-blue;

      .category-text {
        color: $white;
        font-weight: $font-weight-medium;
      }
    }

    &:active {
      transform: scale(0.95);
    }

    .category-text {
      font-size: $font-size-sm;
      color: $dark-gray;
      font-family: $font-family;
      transition: $transition-all;
    }
  }
}

/* 筛选条件栏 - 儿童友好风格 */
.filter-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: $spacing-md;
  margin-bottom: $spacing-xl;
  padding: $spacing-md $spacing-xl;
  @include glass-effect;
  border-radius: $border-radius-xl;
  box-shadow: $shadow-lg;

  .filter-item {
    display: flex;
    align-items: center;

    .filter-label {
      font-size: $font-size-sm;
      color: $medium-gray;
      margin-right: $spacing-xs;
      font-family: $font-family;
    }

    .filter-value {
      font-size: $font-size-sm;
      color: $primary-blue;
      background: rgba(66, 187, 255, 0.1);
      padding: $spacing-xs $spacing-sm;
      border-radius: $border-radius-md;
      font-weight: $font-weight-medium;
      border: 1px solid rgba(66, 187, 255, 0.2);
    }
  }

  .clear-filters {
    display: flex;
    align-items: center;
    gap: $spacing-xs;
    margin-left: auto;
    padding: $spacing-sm $spacing-md;
    border-radius: $border-radius-lg;
    background: $coral-gradient;
    transition: $transition-all;
    box-shadow: $shadow-coral;

    text {
      font-size: $font-size-sm;
      color: $white;
      font-weight: $font-weight-medium;
    }

    &:active {
      transform: scale(0.95);
      box-shadow: 0 2px 8px rgba(255, 149, 149, 0.4);
    }
  }
}

/* 结果统计 - 儿童友好风格 */
.result-stats {
  margin-bottom: $spacing-xl;
  padding: $spacing-md $spacing-lg;
  background: rgba(66, 187, 255, 0.05);
  border-radius: $border-radius-lg;
  border: 1px solid rgba(66, 187, 255, 0.1);

  .stats-text {
    font-size: $font-size-base;
    color: $dark-gray;
    font-weight: $font-weight-medium;
    font-family: $font-family;
  }
}

/* 绘本集列表 - 儿童友好风格 */
.book-section {
  @include card-container;

  .book-grid {
    display: flex;
    flex-wrap: wrap;
    justify-content: left;
    gap: $spacing-sm;

    .book-grid-item {
      width: 30%; // 每行显示3个，与首页保持一致
      margin-bottom: $spacing-lg;
      display: flex;
      flex-direction: column;
      cursor: pointer;
      transition: $transition-all;

      &:active {
        transform: scale(0.95);
      }

      &:hover {
        transform: translateY(-4px);
      }

      .book-cover-container {
        position: relative;
        width: 100%;

        .book-cover-grid {
          width: 100%;
          height: $book-cover-height; // 与首页保持一致
          border-radius: $book-cover-radius;
          background-color: $light-gray;
          box-shadow: $shadow-lg;
          transition: $transition-all;

          &:hover {
            box-shadow: $shadow-xl;
          }
        }

        .book-count-badge {
          position: absolute;
          top: $spacing-sm;
          right: $spacing-sm;
          background: $yellow-gradient;
          color: $dark-gray;
          font-size: $font-size-xs;
          font-weight: $font-weight-semibold;
          padding: $spacing-xs $spacing-sm;
          border-radius: $border-radius-md;
          min-width: 18px;
          text-align: center;
          box-shadow: $shadow-yellow;
          border: 2px solid $white-80;
        }
      }

      .book-title-grid {
        margin-top: $spacing-sm;
        font-size: $font-size-base;
        color: $dark-gray;
        font-weight: $font-weight-medium;
        font-family: $font-family;
        line-height: $line-height-normal;
        @include text-ellipsis-multiline(2);
        height: 40px; // 预留两行的高度
      }

      .book-source-grid {
        margin-top: $spacing-xs;
        font-size: $font-size-sm;
        color: $medium-gray;
      }
    }
  }
}

/* 底部操作区域 */
.bottom-actions {
  padding: $spacing-lg $container-padding $spacing-2xl;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(255, 255, 255, 0.2);
}

/* 加载更多区域 */
.load-more-section {
  @include center-flex;

  .loading-wrapper {
    display: flex;
    align-items: center;
    gap: $spacing-sm;
    padding: $spacing-md $spacing-xl;
    background: rgba(66, 187, 255, 0.05);
    border-radius: $border-radius-xl;

    .loading-text {
      font-size: $font-size-base;
      color: $medium-gray;
      font-family: $font-family;
    }
  }

  .load-more-btn {
    display: flex;
    align-items: center;
    gap: $spacing-sm;
    padding: $spacing-md $spacing-2xl;
    background: $blue-gradient;
    border-radius: $border-radius-xl;
    box-shadow: $shadow-blue;
    transition: $transition-all;
    min-width: 160px;
    justify-content: center;

    .load-more-text {
      font-size: $font-size-base;
      color: $white;
      font-weight: $font-weight-medium;
      font-family: $font-family;
    }

    &:active {
      transform: scale(0.95);
      box-shadow: 0 2px 8px rgba(66, 187, 255, 0.4);
    }
  }
}

/* 没有更多数据 - 儿童友好风格 */
.no-more {
  @include center-flex;
  gap: $spacing-md;
  padding: $spacing-lg 0;
  background: none;

  .no-more-line {
    flex: 1;
    height: 1px;
    background: linear-gradient(to right, transparent, $border-color-light, transparent);
  }

  .no-more-text {
    font-size: $font-size-sm;
    color: $medium-gray;
    font-family: $font-family;
    padding: 0 $spacing-md;
    // background: rgba(255, 255, 255, 0.8);
    border-radius: $border-radius-sm;
  }
}

/* 空状态 - 儿童友好风格 */
.empty-state {
  @include center-flex;
  flex-direction: column;
  padding: 80px $spacing-2xl;
  background: rgba(255, 255, 255, 0.5);
  border-radius: $border-radius-xl;
  margin: $spacing-2xl 0;

  .empty-icon {
    margin-bottom: $spacing-2xl;
    opacity: 0.3;
    padding: $spacing-xl;
    background: rgba(204, 204, 204, 0.1);
    border-radius: $border-radius-full;
  }

  .empty-text {
    font-size: $font-size-lg;
    color: $dark-gray;
    margin-bottom: $spacing-sm;
    font-weight: $font-weight-medium;
    font-family: $font-family;
  }

  .empty-tip {
    font-size: $font-size-base;
    color: $medium-gray;
    font-family: $font-family;
  }
}
</style>
